package com.example.springboot01.config;

import com.example.springboot01.entity.Student;
import com.example.springboot01.entity.Teacher;
import com.example.springboot01.entity.User;
import com.example.springboot01.execs.CustomException;
import com.example.springboot01.model.LoginStatusModel;
import com.example.springboot01.resp.enums.CommonRespEnum;
import com.example.springboot01.service.StudentService;
import com.example.springboot01.service.TeacherService;
import com.example.springboot01.service.UserService;
import com.example.springboot01.util.CustomBeanUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Component
public class SystemInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private TeacherService tService;

    @Resource
    private StudentService sService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        final String status = request.getHeader("token");

        if (status == null) {
            throw new CustomException(CommonRespEnum.UNAUTHORIZED);
        } else {
            User user = userService.getById(status);
            if (user != null) {
                final Integer userType = user.getUserType();
                // 教师
                if (userType == 1) {
                    final Teacher teacher = tService.getByUserId(user.getId());
                    TeacherContextHolder.set(teacher.getId());
                } else if (userType == 0){
                    final Student student = sService.getByUserId(user.getId());
                    StudentContextHolder.set(student.getId());
                }
                return true;
            } else {
                throw new CustomException(CommonRespEnum.SESSIONEXPIRE);
            }

        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TeacherContextHolder.remove();
        StudentContextHolder.remove();
    }
}
